package com.niiwoo.civet.user.service.local.asset;

import com.niiwoo.civet.user.dao.entity.UserCreditInfo;
import com.niiwoo.civet.user.dto.request.asset.AssetCreditResultDTO;
import com.niiwoo.civet.user.enums.CreditEnum;
import com.niiwoo.civet.user.enums.LibraLoanLimitEnum;
import com.niiwoo.civet.user.enums.ProductTypeEnum;
import com.niiwoo.civet.user.service.local.LibraLoanLimitService;
import com.niiwoo.civet.user.service.local.UserCreditService;
import groovy.util.logging.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 资产端授信本地服务
 * @Author LiJian
 * @date 2018/2/22
 */
@Slf4j
@Service
public class AssetCreditService {

    @Autowired
    private UserCreditService userCreditService;

    @Autowired
    private LibraLoanLimitService libraLoanLimitService;


    /**
     * 更新授信信息
     * @param assetCreditResultDTO
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateCreditResult(AssetCreditResultDTO assetCreditResultDTO) {
        UserCreditInfo userCreditInfo = new UserCreditInfo();
        userCreditInfo.setUserId(assetCreditResultDTO.getUserId());
        userCreditInfo.setCreditType(assetCreditResultDTO.getCreditAmountType().getType());
        userCreditInfo.setCreditModelType(assetCreditResultDTO.getCreditModelType().getType());
        userCreditInfo.setCreditTime(assetCreditResultDTO.getCreditTime());
        userCreditInfo.setCreditAmount(assetCreditResultDTO.getCreditAmount());
        userCreditService.updateUserCreditInfo(userCreditInfo);
        // 判断是否小于最小额度
        if(assetCreditResultDTO.getCreditAmount().compareTo(assetCreditResultDTO.getMinAmount()) < 0) {
            ProductTypeEnum productTypeEnum = this.getProductTypeByCreditType(assetCreditResultDTO.getCreditAmountType());
            libraLoanLimitService.addLibraLoanLimit(assetCreditResultDTO.getUserId(), LibraLoanLimitEnum.CREDIT_AMOUNT_LESS, productTypeEnum, assetCreditResultDTO.getLimitDays(), assetCreditResultDTO.getCreditTime());
        }
    }

    private ProductTypeEnum getProductTypeByCreditType( CreditEnum.CreditAmountType creditAmountType) {
        ProductTypeEnum productTypeEnum = null;
        switch (creditAmountType) {
            case SPEED_BORROW:
                productTypeEnum = ProductTypeEnum.SPEED_LOAN;
                break;
            case CARD_NIU:
                productTypeEnum = ProductTypeEnum.CARD_NIU_LOAN;
                break;
            default:
                break;
        }
        return productTypeEnum;
    }
}
